import java.util.PriorityQueue;

public class Demood33 {
    import javafx.scene.effect.Bloom;

import java.util.PriorityQueue;


    class MyTask implements Comparable<MyTask>{
        private Runnable runnable;
        private long time;
        public MyTask(Runnable runnable,long delay){

            this.runnable = runnable;
            this.time = System.currentTimeMillis()+delay;
        }
        public long getTime(){
            return time;
        }

        @Override
        public int compareTo(MyTask o) {
            return (int)(this.time-o.time);
        }
        public void run(){
            runnable.run();
        }
    }

    class MyTimer{
        Object locker = new Object();
        //负责扫描队列,任务的线程
        private Thread t = null;
        //任务队列
        private PriorityQueue<MyTask> queue = new PriorityQueue<>();
        public void schedule(Runnable runnable,long delay) {
            synchronized (locker) {
                MyTask myTask = new MyTask(runnable, delay);
                queue.add(myTask);
            }
        }
        public MyTimer(){
            t =new Thread(()->{
                while(true) {
                    try {
                        synchronized (locker) {
                            while (queue.isEmpty()) {

                                locker.wait();

                            }
                            MyTask task = queue.peek();
                            long time = System.currentTimeMillis();
                            if (time >= task.getTime()) {
                                queue.poll();
                                task.run();
                            } else {
                                locker.wait(System.currentTimeMillis()- time);
                            }
                        }
                    }
                    catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    public class Demod1 {
        public static void main(String[] args) {
            MyTimer myTimer = new MyTimer();
            myTimer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("延时5秒");
                }
            },5000);
            myTimer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("延时3秒");
                }
            },3000);
            myTimer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("延时1秒");
                }
            },1000);
            System.out.println("hello main");
        }

    }

}
